<template>
  <div id="register">
    <div class="register-tab">
      <a href="#" class="active">注册</a>
    </div>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="username">
        <el-input type="text" placeholder="请输入用户名" v-model="ruleForm.username" autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="pass">
        <el-input type="password" placeholder="请输入六至十五位数字或字符" v-model="ruleForm.pass" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input type="password" placeholder="请再次输入密码" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input type="email" placeholder="请输入" v-model="ruleForm.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="isemail">
        <el-input style="width: 50%" type="text" placeholder="请输入" v-model="ruleForm.isemail" autocomplete="off"></el-input>
        <el-button type="primary" @click="getIsemail" :disabled=isTime v-text="isTime ? time  : '获取验证码'"></el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>


<script>
  export default {
    data () {
      //判断用户名是否已存在
      const validateUsername = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入用户名'));
        } else {
          this.$http({
            method: 'post',
            url: '/user/checkName/'+this.ruleForm.username
          }).then(res => {
            if (res.data) {
              callback(new Error('用户名已存在'));
            } else {
              callback();
            }
          })
        }
      };
      //判断密码格式
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          const reg = /^[\w]{6,15}$/i
          const reg1 = /[a-zA-Z]/
          const reg2 = /[0-9]/
          if ( !reg.test(value)) {
            callback(new Error('密码格式不正确'));
          }else {
            if (this.ruleForm.checkPass !== '') {
              this.$refs.ruleForm.validateField('checkPass');
            }
            callback();
          }
        }
      };
      //判断两次密码是否一致
      const validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      //判断邮箱是否已绑定过
      const validateEmail = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入邮箱'));
        } else {
          const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
          if (!reg.test(value)){
            this.checkemail = false
            callback(new Error('邮箱格式错误'));
          }else {
            this.$http({
              method: 'post',
              url: '/user/checkEmail/'+this.ruleForm.email+'/null'
            }).then(res => {
              console.log(res.data);
              this.checkemail = !res.data
              if (res.data) {
                callback(new Error('邮箱已绑定过'));
              } else {
                callback();
              }
            })
          }
        }
      };
      //判断邮箱验证码是否正确
      const validateIsEmail = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入验证码'));
        } else {
          this.$http({
            method: 'post',
            url: '/checkEmailNumber/'+this.ruleForm.isemail,
          }).then(res => {
            if (res.data) {
              callback();
            }else {
              callback(new Error('验证码输入错误'));
            }
          })
        }
      };
      return{
        ruleForm: {
          username: '',
          pass: '',
          checkPass: '',
          email: '',
          isemail: ''
        },
        rules: {
          username: [
            { validator: validateUsername, trigger: 'blur' }
          ],
          pass: [
            { validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            { validator: validatePass2, trigger: 'blur' }
          ],
          email: [
            { validator: validateEmail, trigger: 'blur' }
          ],
          isemail: [
            { validator: validateIsEmail, trigger: 'blur' }
          ]
      },
        isTime:false,
        time: '',
        checkemail: false
      }
    },
    methods: {
      //倒计时
      getCodeTime() {
        this.isTime = true
        let time = 60000;
        let aa = setInterval(()=> {
          const second = Math.floor(time / 1000 % 60);
          this.time=second +  's'
          time -= 1000;
          if (time === -1000) {
            clearTimeout(aa)
            this.isTime = false
          }
        }, 1000)
      },
      //发送邮箱验证码
      getIsemail () {
        if (this.ruleForm.email!==''&&this.checkemail) {
          this.getCodeTime()
          this.$http({
            url: '/sendEmail/'+this.ruleForm.email
          }).then(res=>{
            this.$message('发送成功，请注意查收');
          }).catch(err=>{
            alert("发送失败")
          })
        }
      },
      //注册成功跳会主页
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$http({
              method: 'post',
              url: '/user/register/'+this.ruleForm.username+'/'+this.ruleForm.pass+'/'+this.ruleForm.email,
            }).then(res => {
              this.$message({
                message: '注册成功',
                type: 'success'
              });
              this.$router.replace('/home')
            }).catch(err => {
              console.log(err);
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      //点击重置
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style scoped>
  #register{
    margin: 50px auto;
    width: 600px;
    background-color: #ffffff;
    -webkit-box-shadow: 0 2px 10px 0 rgba(0, 0, 0, 0.1);
    box-shadow: 0 2px 10px 0 rgba(0, 0, 0, 0.1);
  }
  /deep/ .el-form {
    margin: 30px;
    padding-bottom: 30px;
  }
  .register-tab {
    height: 38px;
    text-align: center;
    border-image: linear-gradient(to right, #fff, #CCCCCC, #fff) 1 1;
    border-bottom: 1px solid #CCCCCC;
    padding-top: 20px;
  }

  .register-tab > a.active {
    height: 37px;
    border-bottom: 2px solid #409EFF;
  }
  .register-tab > a {
    display: inline-block;
    height: 38px;
    line-height: 38px;
    padding: 0 30px;
    font-size: 16px;
  }
  a {
    color: #333;
    text-decoration: none;
  }

  /deep/ .el-input{
    width: 80%;
  }
</style>
